package com.gitee.feizns.quickstart.mybatis.plus;

import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.gitee.feizns.quickstart.jackson.Val;
import com.gitee.feizns.quickstart.mybatis.plus.domain.Column;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 常用函数
 * @author feizns
 * @since 2025/3/27
 */
public interface Mysql {

    /**
     * 截断指定类型的表
     * @param type 类型
     * @return int
     */
    static boolean truncate(Class<?> type) {
        return SqlRunner.db().update("TRUNCATE " + TableInfoHelper.getTableInfo(type).getTableName());
    }

    /**
     * 查询
     * @return {@link List}<{@link Map}<{@link String}, {@link Object}>>
     */
    static List<Map<String, Object>> select(String sql) {
        return SqlRunner.db().selectList(sql);
    }

    /**
     * 数据库名称
     * @return {@link String }
     */
    static String database() {
        return (String) SqlRunner.db().selectObj("SELECT DATABASE()");
    }

    /**
     * 所有表
     * @return {@link List }<{@link String }>
     */
    static List<String> tables() {
        return SqlRunner.db().selectObjs("SHOW TABLES").stream()
                .map(obj -> (String) obj)
                .collect(Collectors.toList());
    }

    /**
     * 列
     * @param type 类型
     * @return {@link List }<{@link Column }>
     */
    static List<Column> columns(Class<?> type) {
        List<Map<String, Object>> rows = SqlRunner.db().selectList("SELECT ORDINAL_POSITION as ordinal, COLUMN_NAME as `name`, IS_NULLABLE as `nullable`, DATA_TYPE as dataType, COLUMN_TYPE as columnType, COLUMN_KEY as `key`, column_comment as `comment` FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = (SELECT DATABASE()) AND TABLE_NAME = " + TableInfoHelper.getTableInfo(type).getTableName());
        return rows.stream().map(row -> Val.of(row).asBean(Column.class)).collect(Collectors.toList());
    }

}
